package com.mililoan.console.controller.system;

import java.util.ArrayList;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.mililoan.common.bean.CommonResult;
import com.mililoan.common.bean.JqgridRequest;
import com.mililoan.common.bean.JqgridResultSet;
import com.mililoan.common.bean.JqgridResultSetFactory;
import com.mililoan.common.bean.PageResultSet;
import com.mililoan.common.utils.StackTraceUtil;
import com.mililoan.common.utils.Tool;
import com.mililoan.console.tools.WebUtil;
import com.mililoan.model.system.Actor;
import com.mililoan.model.system.Function;
import com.mililoan.model.system.OpLog;
import com.mililoan.model.system.User;
import com.mililoan.service.module.system.ActorBo;
import com.mililoan.service.module.system.FuncBo;
import com.mililoan.service.module.system.OpLogBo;
import com.mililoan.service.module.system.UserBo;

/**
 * @ClassName: UserAction
 * @Description: 账户管理
 * @author ChenYi 2016年5月5日 上午11:50:32
 *
 */
@Controller
@RequestMapping("/user")
public class UserAction {
	private static Logger LOGGER = LoggerFactory.getLogger(UserAction.class);
	private static final String	MOUDLE	= "sysmrg";
	@Autowired
	private UserBo userBo;
	@Autowired
	private ActorBo actorBo;
	@Autowired
	private FuncBo funcBo;
	@Autowired
	private OpLogBo logBo;

	/**
	 * @Title: queryNew
	 * @Description: 跳转到查询账户信息页面
	 * @author 
	 * @return
	 */
	@RequestMapping("/toUserList.do")
	public String toUserList(Model model) {
		LOGGER.info("跳转到查询账户信息页面");
		return MOUDLE + "/userList";
	}
	
	/**
	 * @Title: showUpdate
	 * @Description: 打开修改页面
	 * @author
	 * @return
	 */
	@RequestMapping("/toUpdateUser.do")
	public String toUpdateUser(@RequestParam(value="userId", required = false) String userId, Model model){
		LOGGER.info("跳转到账户信息新建或编辑页面");
		User user = null;
		if(null != userId){
			user = userBo.getUserById(Tool.parseLong(userId));
		}
		model.addAttribute("user", user);
		return MOUDLE + "/userUpdate";
	}
	
	/**
	 * @Title: showAction
	 * @Description: 打开用户权限设置页面
	 * @author
	 * @return
	 */
	@RequestMapping("/showAction.do")
	public String showAction(@RequestParam(value="userId", required = false) Long userId, Model model){
		LOGGER.info("跳转到用户权限设置页面");
		User userWithActor = userBo.getUserWithActor(userId);
		ArrayList<Actor> actors = actorBo.getAllActors();
		ArrayList<Function> modules = funcBo.getAllModules();
		ArrayList<Function> funcs =  funcBo.getAllFuncs();
		
		model.addAttribute("user", userWithActor);
		model.addAttribute("actors", actors);
		model.addAttribute("funcs", funcs);
		model.addAttribute("modules", modules);

		return MOUDLE + "/userActor";
	}
	
	/**
	 * @Title: queryAjax
	 * @Description: 查询账户列表信息
	 * @author 
	 * @return
	 */
	@RequestMapping("queryUserList.do")
	@ResponseBody
	public JqgridResultSet<User> queryUserList(@RequestBody JqgridRequest<User> jqgridRequest) {
		User user = jqgridRequest.getObj();
		if (null == user) {
			user = new User();
//			User sessionUser = WebUtil.getSessionUser();
//			user.setDepartmentCode(sessionUser.getDepartmentCode());
//			user.setDepartmentName(sessionUser.getDepartmentName());
		}

		PageResultSet<User> prs = userBo.query(user, jqgridRequest.getPage(), jqgridRequest.getRows());
		return JqgridResultSetFactory.toJqgridResultSet(prs);
	}
	
	/**
	 * @Description 新增/修改帐户信息功能
	 * @param User
	 * @return commonResult
	 * @author 
	 * @throws Exception 
	 */
	@RequestMapping(value = "/updateUser.do", method = RequestMethod.POST)
	@ResponseBody
	public CommonResult updateUser(@RequestBody User user) throws Exception {
		CommonResult commonResult = null;
		User userObj = null;
		//获取当前session用户
		User sessionUser = WebUtil.getSessionUser();
		try{
			if(user.getId()==0){
				userObj = new User();
				//前台取数
				userObj.setUserAcct(user.getUserAcct());
				userObj.setUserPwd(user.getUserPwd());
				userObj.setUserName(user.getUserName());
				userObj.setSex(user.getSex());
				userObj.setDepartmentCode(user.getDepartmentCode());
				userObj.setTelCitycode(user.getTelCitycode());
				userObj.setTelExtension(user.getTelExtension());
				userObj.setTelLocalnumber(user.getTelLocalnumber());
				userObj.setEmail(user.getEmail());
				userObj.setMobile(user.getMobile());
				userObj.setIsvalid("1");
				userObj.setDepartmentCode(sessionUser.getDepartmentCode());
				
				if(null!=userBo.addUser(userObj)){
					commonResult = new CommonResult();
					commonResult.setResultCode(CommonResult.SUCCESS);
					commonResult.setMessage("新增系统账号成功!");
				} else {
					commonResult = new CommonResult();
					commonResult.setResultCode(CommonResult.FAIL);
					commonResult.setMessage("新增系统账号成功!");
				};
			} else {
				userObj = this.userBo.getUserById(user.getId());
				//前台取数
				userObj.setUserAcct(user.getUserAcct());
				userObj.setUserPwd(user.getUserPwd());
				userObj.setUserName(user.getUserName());
				userObj.setSex(user.getSex());
//				userObj.setDepartmentCode(user.getDepartmentCode());
				userObj.setTelCitycode(user.getTelCitycode());
				userObj.setTelExtension(user.getTelExtension());
				userObj.setTelLocalnumber(user.getTelLocalnumber());
				userObj.setEmail(user.getEmail());
				userObj.setMobile(user.getMobile());
				
				if(null!=userBo.updateUser(userObj)){
					commonResult = new CommonResult();
					commonResult.setResultCode(CommonResult.SUCCESS);
					commonResult.setMessage("修改系统账号成功!");
				} else {
					commonResult = new CommonResult();
					commonResult.setResultCode(CommonResult.FAIL);
					commonResult.setMessage("修改系统账号成功!");
				}
			}
			return commonResult;
		} catch(Exception e){
			LOGGER.error(StackTraceUtil.getStackTrace(e));
			throw new Exception(e);
		}
	}
	
	/**
	 * @Description 删除用户账户功能
	 * @param user
	 * @return commonResult
	 * @author
	 * @throws Exception 
	 */
	@RequestMapping(value = "/delUser.do", method = RequestMethod.POST)
	@ResponseBody
	public CommonResult delUser(@RequestBody User user) throws Exception {
		CommonResult commonResult = null;
		try{
			if(userBo.delUser(user.getId())!=null){
				commonResult = new CommonResult();	
				commonResult.setResultCode(CommonResult.SUCCESS);	
				commonResult.setMessage("删除系统账户成功!");
			}else{	
				commonResult = new CommonResult();		
				commonResult.setResultCode(CommonResult.FAIL);	
				commonResult.setMessage("删除系统账户失败!");
			}
			return commonResult;
		}catch(Exception e){
			LOGGER.error(StackTraceUtil.getStackTrace(e));
			throw new Exception(e);
		}
	}
	
	/**
	 * 修改用户角色
	 * @throws Exception 
	 */
	@RequestMapping("updateActor.do")
	@ResponseBody
	public CommonResult updateActor(@RequestBody User user) throws Exception {
		User sessionUser = WebUtil.getSessionUser();
		CommonResult commonResult = new CommonResult();
		OpLog opLog = new OpLog();
		// 验证互斥权限（按模块）
//		if (!userBo.checkFuns(user.getActorCodes(), user.getFunCodes())) {
//			commonResult.setResultCode("0");
//			commonResult.setMessage("权限互斥");
//		}

		user.arrToList();

		if (userBo.updateActor(user)) {
			LOGGER.info("用户角色修改成功！"+sessionUser.getUserAcct());
			commonResult.setResultCode(CommonResult.SUCCESS);
			commonResult.setMessage("用户角色修改成功");
		} else {
			LOGGER.info("用户角色修改失败！"+sessionUser.getUserAcct());
			commonResult.setResultCode(CommonResult.FAIL);
			commonResult.setMessage("用户角色修改失败");
		}
		return commonResult;
	}
}
